package cn.com.cetccst.appstore.jssdk;

import android.content.Context;

import com.google.gson.annotations.SerializedName;

import cn.com.cetccst.appstore.jssdk.viewmodel.JSSDKViewModel;
import cn.com.cetccst.appstore.tools.Utils;


public class ActionDownloadFileProgress extends ActionDownloadFile {

    private Response listener;
    /**
     * Details from the last time we pushed a database update.
     */
    private long mLastUpdateBytes = 0;
    private long mLastUpdateTime = 0;
    /**
     * The minimum amount of progress that has to be done before the progress bar gets updated
     */
    public static final int MIN_PROGRESS_STEP = 64 * 1024;
    /**
     * The minimum amount of time that has to elapse before the progress bar gets updated, in ms
     */
    public static final long MIN_PROGRESS_TIME = 2000;

    ActionDownloadFileProgress(Context context, CXApiImplInnerApp icxapi, String parameters, JSSDKViewModel jssdkViewModel) {
        super(context, icxapi, parameters, jssdkViewModel);
    }

    public void handleAction(Response callback, Response listener) {
        this.listener = listener;
        handleAction(callback);
    }

    static class ProgressData {
        @SerializedName("currentBytes")
        long currentBytes;
        @SerializedName("totalBytes")
        long totalBytes;
        @SerializedName("progress")
        long progress;
        @SerializedName("tag")
        String tag;
    }

    @Override
    protected void notifyProcess(int currentBytes) {
        long now = System.currentTimeMillis();

        final long bytesDelta = currentBytes - mLastUpdateBytes;
        final long timeDelta = now - mLastUpdateTime;
        if (bytesDelta > MIN_PROGRESS_STEP && timeDelta > MIN_PROGRESS_TIME
                || currentBytes == totalSize) {
            mLastUpdateBytes = currentBytes;
            mLastUpdateTime = now;
            notifyJS();
        }

    }

    private void notifyJS() {
        if (listener != null) {
            ProgressData progressData = new ProgressData();
            progressData.tag = para.url;
            progressData.currentBytes = mLastUpdateBytes;
            progressData.totalBytes = totalSize;
            progressData.progress = totalSize > 0 ? mLastUpdateBytes * 100 / totalSize : 0;
            listener.setRespJson(Utils.getGson().toJson(progressData));
        }
    }
}
